import {Body, Controller, Ctx, Delete, Flow, Get, Params, Post, Put, Query} from 'koa-ts-controllers'
import {Context} from "koa";
import authorization from "../middlewares/authorization";
import {getandValidateBoardList, GetListsQuery, PostAddListBody, PutUpdateList} from "../validators/BoardList";
import {BoardList as BoardListModel} from "../models/BoardList";
import {getandValidateBoard} from "../validators/Board";

@Controller('/list')
@Flow([authorization])
export class BoardListController {
    @Post('')
    public async addList(@Ctx() ctx: Context, @Body() body: PostAddListBody) {
        let {boardId, name} = body;
        let maxOrderBoardList = await BoardListModel.findOne({
            where: {
                boardId
            },
            order: [['order', 'desc']]
        });
        await getandValidateBoard(boardId, ctx.userInfo.id);
        let boardList = new BoardListModel();
        boardList.userId = ctx.userInfo.id;
        boardList.boardId = boardId;
        boardList.name = name;
        boardList.order = maxOrderBoardList ? maxOrderBoardList.order + 65535 : 65535;
        await boardList.save();
        return boardList;
    }

    @Get('')
    public async getLists(@Ctx() ctx: Context, @Query() query: GetListsQuery) {
        let {boardId} = query;
        await getandValidateBoard(boardId, ctx.userInfo.id)
        let boardList = await BoardListModel.findAll({
            where: {
                boardId
            },
            order: [['order', 'asc']]
        })
        return boardList;
    }

    @Get('/:id(\\d+)')
    public async getList(@Ctx() ctx: Context, @Params('id') id: number) {
        console.log(ctx.userInfo.id+"dayin")
        let boardList = await getandValidateBoardList(id, ctx.userInfo.id)
        return boardList
    }

    @Put('/:id(\\d+)')
    public async updateList(@Ctx() ctx: Context, @Params('id')id: number, @Body() body: PutUpdateList) {
        let {boardId, name, order} = body
        let boardList = await getandValidateBoardList(id, ctx.userInfo.id)
        boardList.boardId = boardId || boardList.boardId;
        boardList.name = name || boardList.name;
        boardList.order = order || boardList.order;
        await boardList.save();
        ctx.status = 204;
        return

    }

    @Delete('/:id(\\d+)')
    public async deleteList(@Ctx() ctx: Context, @Params('id') id: number) {
        let boardList = await getandValidateBoardList(id, ctx.userInfo.id)
        boardList.destroy();
        ctx.status = 204;
        return
    }
}
